package com.monkeygroup.mygoplus.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;




import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.common.AppConfig;

public class YTools {

	public static void call(Context context, String phone) {
		Intent intent = new Intent(Intent.ACTION_CALL,
				Uri.parse("tel:" + phone));
		context.startActivity(intent);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	@SuppressLint("NewApi")
	public static Point getScreenSize(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		Point outSize = new Point();
		display.getSize(outSize);
		return outSize;
	}

	public static int getScreenWidth(Activity activity) {
		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）

		return width;
	}

	public static float getScreenDensity(Activity activity) {
		float scale = activity.getResources().getDisplayMetrics().density;
		return scale;
	}

	public static String safeString(String source) {
		if (source == null || source.length() == 0)
			return "";

		String re = source.trim().replace("}", "").replace("{", "")
				.replace("<", "").replace(">", "").replace("]", "")
				.replace("[", "").replace("\"", "");
		return re;
	}

	public static String safeString(EditText et) {
		String source = et.getText().toString();
		if (source.length() == 0) {
			return "";
		} else {
			String re = source.trim().replace("}", "").replace("{", "")
					.replace("<", "").replace(">", "").replace("]", "")
					.replace("[", "").replace("\"", "");
			return re;
		}
	}

	public static Point getWidgeSize(View v) {
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		v.measure(w, h);
		int height = v.getMeasuredHeight();
		int width = v.getMeasuredWidth();
		return new Point(height, width);
	}

	public static int getTextLength(TextView textView, String text) {
		TextPaint paint = textView.getPaint();
		// 得到使用该paint写上text的时�?像素为多�?
		float textLength = paint.measureText(text);
		return (int) (textLength);
	}

	public static String getFileNameFromUrl(String url) {
		if (url == null || url.equals(""))
			return url;
		int p = url.lastIndexOf("/");
		if (p > -1) {
			return url.substring(p + 1);
		} else {
			return url;
		}
	}

	public static SharedPreferences getSharePreferences(Context context,
			String name) {
		SharedPreferences sh = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		return sh;
	}

	public static boolean checkConnection(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.isConnected()) {
			return true;
		}
		return false;
	}

	public static void closeInputWindow(Activity activity) {
		try {
			InputMethodManager inputMethodManager = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(activity
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {

		}
	}

	public static double formatMoney(double m) {
		String m1 = String.format("%.2f", m);
		return Double.parseDouble(m1);
	}

	public static String getDeviceid(Context context) {
		SharedPreferences sh = context.getSharedPreferences("DEVICEINFO",
				Context.MODE_PRIVATE);
		String deviceid = sh.getString("deviceid", "");
		if (deviceid.length() == 0) {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			deviceid = "" + tm.getDeviceId();
			if (deviceid.length() == 0) {
				deviceid = "1234567890";
			} else {
				SharedPreferences.Editor edit = sh.edit();
				edit.putString("deviceid", deviceid);
				edit.commit();
			}
		}
		return deviceid;
	}

	/**
	 * 缩放图片
	 * 
	 * @param source
	 * @param toFile
	 * @return
	 */

	public static boolean zoomPic(File source, File toFile) {
		if (toFile.exists()) {
			toFile.delete();
		}

		boolean flag = true;
		try {
			FileOutputStream out = new FileOutputStream(toFile);
			Bitmap bitmap = BitmapFactory.decodeFile(source.toString());
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();

			if (width > 540) {
				// 缩放
				Matrix matrix = new Matrix();
				float k = 1.0f;// 缩放率
				// 宽比高大
				k = 540f / width;

				matrix.postScale(k, k);
				Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width,
						height, matrix, true);
				newbmp.compress(CompressFormat.PNG, 100, out);
				out.close();
				newbmp.recycle();
				bitmap.recycle();
			} else {
				// 直接 COPY
				InputStream fosfrom = new FileInputStream(source);
				OutputStream fosto = new FileOutputStream(toFile);
				byte bt[] = new byte[1024];
				int c;
				while ((c = fosfrom.read(bt)) > 0) {
					fosto.write(bt, 0, c);
				}
				fosfrom.close();
				fosto.close();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	public static File getImageFromSys(Activity activity, Uri imageFilePath) {
		try {
			File re = null;
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = activity.getContentResolver().query(imageFilePath,
					proj, null, null, null);
			if (cursor != null && cursor.moveToFirst()) {
				String path = cursor.getString(0);
				re = new File(path);
			}
			cursor.close();
			return re;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void startClock(Activity activity) {
		final SharedPreferences sh = activity.getSharedPreferences("sysclock",
				Context.MODE_PRIVATE);
		String activityName = sh.getString("activityName", null);
		String clockPackageName = sh.getString("clockPackageName", null);

		if (clockPackageName == null || activityName == null) {
			Toast.makeText(activity, "启动闹钟失败！", Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = new Intent();
			intent.setComponent(new ComponentName(clockPackageName,
					activityName));
			activity.startActivity(intent);
		}
	}

	/**
	 * 初始化闹钟程序
	 * 
	 * @param activity
	 */
	public static void initClock(final Activity activity) {
		final SharedPreferences sh = activity.getSharedPreferences("sysclock",
				Context.MODE_PRIVATE);
		String activityName = sh.getString("activityName", null);
		String clockPackageName = sh.getString("clockPackageName", null);

		if (clockPackageName == null || activityName == null) {
			// 需要初始化
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					List<PackageInfo> allPackageInfos = activity
							.getPackageManager().getInstalledPackages(
									PackageManager.GET_UNINSTALLED_PACKAGES
											| PackageManager.GET_ACTIVITIES); // 取得系统安装所有软件信息
					for (int i = 0; i < allPackageInfos.size(); i++) {// 循环取出所有软件信息
						PackageInfo temp = allPackageInfos.get(i);
						ApplicationInfo appInfo = temp.applicationInfo;// 得到每个软件信息
						if ((appInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
								|| (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
							// 系统软件
							String packageName = temp.packageName;
							if (packageName.indexOf("clock") != -1) {
								if (!(packageName.indexOf("widget") != -1)) {
									// 找到系统闹钟了
									ActivityInfo activityInfo = temp.activities[0];// 取出activity信息
									String aname = activityInfo.name;// 取出activity名字
									String cname = packageName;

									// 记录
									SharedPreferences.Editor edit = sh.edit();
									edit.putString("activityName", aname);
									edit.putString("clockPackageName", cname);
									edit.commit();
									break;
								}
							}

						}
					}
				}

			}.start();
		}
	}

	public static Bitmap toRoundCorner(Bitmap bitmap , float ratio) {
//		 BitmapFactory.Options bfOpt= new BitmapFactory.Options();
//		   bfOpt.inPreferredConfig = Bitmap.Config.ARGB_8888;
//		   bfOpt.inSampleSize =1;  
//		Bitmap bitmap = BitmapFactory.decodeFile(source,bfOpt);
		
		
//		Bitmap bitmap = BitmapFactory.decodeFile(source);
		Log.e("bitmapbitmap", ""+bitmap);
		if(bitmap==null){
			return null;
		}
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
				bitmap.getHeight() / ratio, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;

	}

	/**
	 * 调用照相机，返回编码3000
	 * 
	 * @param activity
	 * @param
	 *
	 */
	public static void showCamera(Activity activity, String filename)
			throws Exception {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		
		// 下面这句指定调用相机拍照后的照片存储的路径
		File filePath = YFileManager.getLeaveMsgPicsCacheFile(filename);

		if (null != filePath) {
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
			intent.putExtra("type","type");
			Log.i("tongke", "准备照相......");
			activity.startActivityForResult(intent, AppConfig.CAMERA_CODE);
			Log.i("gezi", "等待......");
		} else {
			return;
		}

	}
	
	public static void showPicker(Activity activity){
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_PICK);
		activity.startActivityForResult(intent, AppConfig.ALBUM);
	}

	/**
	 * 判断字符串是否是整数
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是浮点数
	 */
	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是数字
	 */
	public static boolean IsNumber(String value) {
		return isInteger(value) || isDouble(value);
	}
	
	/**
	 * 功能说明:判断是否是小时
	 * 输入参数:
	 * 输出参数: 
	 * 作        者:qidongbo
	 * 创建日期:2015-10-23上午11:33:33
	 */
	public static boolean IsHour(String value) {
		if (value == null)
		{
			return false;
		}
		
		if (isInteger(value) == false)
		{
			return false;
		}
  		else
		{
			int iTempValue = Integer.parseInt(value);
			
			if (iTempValue >= 0 && iTempValue < 24)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	
	/**
	 * 功能说明:判断是否是分钟
	 * 输入参数:
	 * 输出参数: 
	 * 作        者:qidongbo
	 * 创建日期:2015-10-23上午11:33:33
	 */
	public static boolean IsMinute(String value) {
		if (value == null)
		{
			return false;
		}
		
		if (isInteger(value) == false)
		{
			return false;
		}
		else
		{
			int iTempValue = Integer.parseInt(value);
			
			if (iTempValue >= 0 && iTempValue < 60)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	
	/**
	 * 功能说明:是否是年
	 * 输入参数:
	 * 输出参数: 
	 * 作        者:qidongbo
	 * 创建日期:2015-10-29上午11:55:19
	 */
	public static boolean IsYear(String value)
	{
		if(value == null )
		{
			return false;
		}
		
		Log.i("gezi", "year =" + value);
		
		if (value.length() != 4)
		{
			return false;
		}
		
		return true;
	}
	
	
	/**
	 * 功能说明:是否是月
	 * 输入参数:
	 * 输出参数: 
	 * 作        者:qidongbo
	 * 创建日期:2015-10-29上午11:55:19
	 */
	public static boolean IsMonth(String value)
	{
		if(value == null )
		{
			return false;
		}
		
		Log.i("gezi", "month =" + value);
		
		if (isInteger(value) == true)
		{
			int iMonth = Integer.parseInt(value);
			if (iMonth >=1 && iMonth <=12)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 功能说明:是否是天
	 * 输入参数:
	 * 输出参数: 
	 * 作        者:qidongbo
	 * 创建日期:2015-10-29上午11:55:19
	 */
	@SuppressLint("SimpleDateFormat")
	public static boolean IsDate(String year, String month, String date)
	{
		if(year == null || month == null || date == null)
		{
			Log.i("gezi", "year == null || month == null || date == null");
			return false;
		}
		
		if (IsYear(year) == false)
		{
			return false;
		}
		
		if (IsMonth(month) == false)
		{
			return false;
		}
		
		if (month.length() == 1)
		{
			month = "0" + month;
		}
		
		if (date.length() == 1)
		{
			date = "0" + date;
		}
		
		// 不能小于今天
		//Calendar c=Calendar.getInstance();
		//String strToday = "" + c.YEAR + "" + c.MONTH + "" + c.DAY_OF_MONTH;
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");
		Date curDate = new Date(System.currentTimeMillis());
		String strToday = formatter.format(curDate);
		
		String strTemp  = year + month + date;
		Log.i("gezi", "today:" + strToday);
		Log.i("gezi", "input:" + strTemp);
		if (strToday.compareTo(strTemp) >= 0)
		{
			return false;
		}
		
		if (isInteger(date) == true)
		{
			int iMonth = Integer.parseInt(month);
			int idate  = Integer.parseInt(date);
			if (iMonth == 1 || iMonth == 3 || iMonth == 5 || iMonth == 7 || iMonth == 8 || iMonth == 10 || iMonth == 12)
			{
				if (idate >=1 && idate <= 31)
				{
				    return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				if (idate >=1 && idate <= 30)
				{
				    return true;
				}
				else
				{
					return false;
				}
			}
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 功能说明:获取当前时间  
	 * 输入参数:
	 * 输出参数:yyyy-mm-dd hh:mm:ss
	 * 作        者:qidongbo
	 * 创建日期:2015-10-29下午1:21:51
	 */
	@SuppressLint("SimpleDateFormat")
	public static String getCurrentTime()
	{
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日     HH:mm");
		Date curDate = new Date(System.currentTimeMillis());
		String strToday = formatter.format(curDate);
		
		return strToday;
	}
}
